🔁 Top 30 Python List Methods You Should Know

 

🔁 Top 30 Python List Methods You Should Know 🧠📋

1. append() – Add element to the end

lst = [1, 2] lst.append(3) # Output: [1, 2, 3]

2. extend() – Add multiple elements from another list

lst = [1, 2] lst.extend([3, 4]) # Output: [1, 2, 3, 4]

3. insert() – Insert element at specific index

lst = [1, 3] lst.insert(1, 2) # Output: [1, 2, 3]

4. remove() – Remove first occurrence of a value

lst = [1, 2, 3] lst.remove(2) # Output: [1, 3]

5. pop() – Remove element at index (default last)

lst = [1, 2, 3] lst.pop(1) # Output: 2, list becomes [1, 3]

6. index() – Find index of first occurrence

lst = [10, 20, 30] lst.index(20) # Output: 1

7. count() – Count occurrences of value

lst = [1, 1, 2] lst.count(1) # Output: 2

8. sort() – Sort list in ascending order (in-place)

lst = [3, 1, 2] lst.sort() # Output: [1, 2, 3]

9. reverse() – Reverse list (in-place)

lst = [1, 2, 3] lst.reverse() # Output: [3, 2, 1]

10. copy() – Create a shallow copy

old_list = [1, 2, 3] new_list = old_list.copy() # Output: [1, 2, 3]

11. clear() – Remove all elements

lst = [1, 2, 3] lst.clear() # Output: []

12. len() – Get length of list

len([1, 2, 3]) # Output: 3

13. sum() – Sum numeric elements

sum([1, 2, 3]) # Output: 6

14. min() – Minimum value

min([5, 2, 8]) # Output: 2

15. max() – Maximum value

max([5, 2, 8]) # Output: 8

16. any() – Check if any element is True

any([0, 1, 0]) # Output: True

17. all() – Check if all elements are True

all([1, 1, 1]) # Output: True

18. reversed() – Return iterator in reverse

list(reversed([1, 2, 3])) # Output: [3, 2, 1]

19. sorted() – Return new sorted list

sorted([3, 1, 2]) # Output: [1, 2, 3]

20. enumerate() – Get index and value in loop

for i, val in enumerate(['a','b']): print(i, val) # Output: 0 a, 1 b

21. zip() – Combine multiple lists

list(zip([1,2],[3,4])) # Output: [(1,3),(2,4)]

22. filter() – Filter elements by condition

list(filter(lambda x: x>2, [1,2,3,4])) # Output: [3,4]

23. map() – Apply function to each element

list(map(str.upper, ['a','b'])) # Output: ['A','B']

24. slice – Access part of list

lst = [0,1,2,3,4] lst[1:4] # Output: [1,2,3]

25. copy.deepcopy() – Deep copy nested lists

import copy lst = [[1,2],[3,4]] copy.deepcopy(lst) # Independent copy

26. isinstance() – Check if object is a list

isinstance([1,2], list) # Output: True

27. sum() with generator – Sum of filtered values

sum(x for x in [1,2,3] if x>1) # Output: 5

28. del – Delete element or slice

lst = [1,2,3] del lst[1] # lst becomes [1,3]

29. * operator – Repeat list

[1,2]*3 # Output: [1,2,1,2,1,2]

30. list() – Convert iterable to list

list((1,2,3)) # Output: [1,2,3]

Comments

Popular posts from this blog

Python Project 7: Read & Write JSON Files

✅ Python – Quick Start Guide for Beginners